package com.test;

import com.test.definition.BeanDefinition;
import com.test.exception.BeansException;
import com.test.factory.AbstractAutowireCapableBeanFactory;

import java.lang.reflect.Constructor;
import java.util.Arrays;

public class ConstructorResolver {
    private final AbstractAutowireCapableBeanFactory beanFactory;

    public ConstructorResolver(AbstractAutowireCapableBeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    public BeanInstantiationContext autowireConstructor(String beanName, BeanDefinition beanDefinition, Constructor<?>[] constructors, Object[] args) {
        System.out.println("开始解析构造函数：" + beanName + ", 构造函数数量：" + (constructors!=null ? constructors.length : 0));
        if (constructors == null || constructors.length == 0){
            try{
                Constructor<?> defualtConstructor = beanDefinition.getBeanClass().getDeclaredConstructor();
                System.out.println("使用默认构造函数："+ defualtConstructor);
                return new BeanInstantiationContext(defualtConstructor, new Object[0]);
            }catch (NoSuchMethodException e){
                throw new BeansException("没有找到默认构造函数：" + beanDefinition.getBeanClass().getName(), e);
            }
        }

        if (args != null && args.length > 0){
            System.out.println("提供了参数，尝试匹配构造函数：" + Arrays.toString(args));
            for (Constructor<?> constructor : constructors) {
                if (constructor.getParameterTypes().length == args.length){
                    Class<?>[] paramTypes = constructor.getParameterTypes();
                    boolean match = true;
                    for (int i = 0; i < args.length; i++){
                        if (args[i] != null && !paramTypes[i].isInstance(args[i])){
                            match = false;
                            break;
                        }
                    }
                    if (match){
                        System.out.println("找到匹配的构造函数：" + constructor);
                        return new BeanInstantiationContext(constructor, args);
                    }
                }
            }
        }
        throw new BeansException("没有找到匹配的构造函数：" + beanName);
    }
}
